package com.isyscore.os.etl.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.isyscore.boot.login.LoginUserManager;
import com.isyscore.boot.login.properties.LoginProperties;
import com.isyscore.device.common.util.JsonMapper;
import com.isyscore.os.permission.common.constants.PermissionConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 仿造@FeignConfiguration实现功能
 * @author : zhan9yn
 * @version : 1.0
 * @date : 2022/3/1 5:51 下午
 */
@Log4j2
public class InitCrossServerConfig implements RequestInterceptor {

    @Autowired
    private LoginUserManager loginUserManager;

    @Autowired
    private LoginProperties prop;

    private String permissionUrl="http://isc-permission-service:32100/api/permission/auth/os/login";
    private static String USER ="app_7d079584c660";
    private static String PASS ="XuWiWZRiQRjw4HoAQ19fuW0iavViO4Mi+xhyTIIx0Wmf6zeBcVaOfSaNGOlmHXOJ";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 透传isc-tenant-id的token
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (ObjectUtil.isNotNull(attributes)) {
            HttpServletRequest request = attributes.getRequest();
            if (ObjectUtil.isNotNull(request)) {
                // 遍历设置 也可从request取出整个Header 写到RequestTemplate 中
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        if (PermissionConstants.Header.CROSS_TENANT_TENANTID_KEY.equals(name)) {
                            requestTemplate.header(name, values);
                        }
                    }
                }
            }
        }
        //如果存在登录用户，直接取登录用户的token，否则取配置的跨服务调用用户token，后台调度loginUser只有tenantId信息
        if (loginUserManager.getCurrentLoginUser() != null&&loginUserManager.getCurrentLoginUser().getToken()!=null) {
            requestTemplate.header(PermissionConstants.Header.TOKEN, loginUserManager.getCurrentLoginUser().getToken());
        }else{
            requestTemplate.header(PermissionConstants.Header.TOKEN, fetchToken());
        }
    }

    private  String fetchToken(){
        Map body = new HashMap<>();
        body.put("loginName",USER);
        body.put("password",PASS);
        String token;
        try {
            String response = HttpUtil.post(permissionUrl, JsonMapper.toAlwaysJson(body));
            JSONObject jsonObject = JSONObject.parseObject(response);
            if(0==jsonObject.getInteger("code")){
                token = jsonObject.getJSONObject("data").getString("token");
            }else{
                log.error("获取token失败{}",response);
                throw new IllegalStateException("获取token失败");
            }
        }catch (Exception e){
            log.error("获取token失败{}",e.getMessage());
            throw new IllegalStateException("获取token失败");
        }
        return token;
    }
}
